package com.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.ClassBean;
import com.project.bean.StudentBean;
import com.project.service.IStudentService;
import com.project.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

@RestController
@RequestMapping("student")
public class StudentController {
    @Autowired
    private IStudentService service;

    @RequestMapping("findByItem")
    public PageInfo<StudentBean> findByItem(int pageNO,
         String name,Integer startGrade,Integer endGrade){
        return service.findByItem(pageNO,name,startGrade,endGrade);
    }

    @RequestMapping("/del")
    public String del(int id){
        service.del(id);
        return "ok";
    }

    @RequestMapping("/findById")
    public StudentBean findById(int id){
        StudentBean  student = service.findById(id);
        return student;
    }

    @RequestMapping("update")
    public String update(int id,String phone,int classId){
        service.update(id,phone,classId);
        return "ok";
    }

    @RequestMapping("add")
    public String add(@Valid StudentBean student, BindingResult result,
                      @RequestParam("faceFile")MultipartFile mf) throws Exception{
        if(result.hasErrors()){
            ObjectMapper om = new ObjectMapper();
            return om.writeValueAsString(result.getFieldErrors());
        }

        String fileName = UploadUtil.upload(mf,"face");
        student.setFace(fileName);

        service.add(student);
        return "ok";
    }
}
